package util;

import bean.DealRecord;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

/**
 * 一些和交易记录相关的方法，用于DealRecordServlet,AlipayServlet,AlipayNotifyServlet
 *
 * @author dsf
 */
public class DealRecordUtil {
    /**
     * 数据合法性检测
     *
     * @param dr      the dr
     * @param balance the balance
     * @return boolean boolean
     */
    public static boolean dataCheck(DealRecord dr, String balance) {
        boolean dataSafe = false;
        if (StringUtil.isNotEmpty(dr.getUserId()) && StringUtil.isNotEmpty(dr.getMoney())
            && StringUtil.isNotEmpty(balance)) {
            try {
                // `userId` int(8) unsigned NOT NULL AUTO_INCREMENT
                int userId_i = Integer.parseInt(dr.getUserId());
                if (userId_i > 0 && userId_i < 100000000) {
                    // `money` decimal(8,2) NOT NULL
                    float money_f = Float.parseFloat(dr.getMoney());
                    // `balance` decimal(8,2) unsigned zerofill NOT NULL
                    float balence_f = Float.parseFloat(balance);
                    if (money_f > 0 && ((money_f + balence_f) <= 999999.99)) {
                        if (balence_f <= 999999.99) {
                            dataSafe = true;
                        } else {
                            System.out.println("DataError：illegal balance！");
                        }
                    } else {
                        System.out.println("DataError：illegal money！");
                    }
                } else {
                    System.out.println("DataError：illegal userid！");
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("DataError：the key para is null！");
        }
        return dataSafe;
    }

    /**
     * 用于获取充值后的余额
     *
     * @param balance the balance
     * @return string string
     */
    public static String formatBalance(String balance) {
        if (StringUtil.isNotEmpty(balance)) {
            balance = balance.replaceFirst("^0*", "");
        }
        return balance;
    }

    /**
     * 获取充值后的余额
     *
     * @param balance the balance
     * @param money   the money
     * @return cur balance
     */
    public static String getCurBalance(String balance, String money) {
        float curBalance = 0;
        try {
            float balance_f = Float.parseFloat(balance);
            float money_f = Float.parseFloat(money);
            curBalance = balance_f + money_f;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return curBalance + "";
    }

    /**
     * 依据拼接规则生成交易记录的id号 拼接规则：userId+actionType+actionTime
     *
     * @param userId     the user id
     * @param actionType the action type
     * @param actionTime the action time
     * @return dr id
     */
    public static String getDrId(String userId, String actionType, String actionTime) {
        StringBuffer drId = new StringBuffer();
        drId.append(userId);
        drId.append(actionType);
        drId.append(actionTime);
        return drId.toString();
    }

    /**
     * 获取当前时间（服务器时间）
     *
     * @return time now
     */
    public static String getTimeNow() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(new Date());
    }

    /**
     * 确定是否执行删除方法（至少每隔两天执行）
     *
     * @return boolean boolean
     */
    public static boolean isDeleteTime() {
        boolean delTime = false;
        String now = getTimeNow().substring(6, 8);
        try {
            int now_i = Integer.parseInt(now);
            if (now_i % 5 == 0) {
                delTime = true;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return delTime;
    }

    /**
     * 检测是否是单边账。
     * 原理：如果商户反馈给支付宝的字符不是success这7个字符，支付宝服务器会不断重发通知，直到超过24小时22分钟。一般情况下，25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）；
     *
     * @param actionTime the action time
     * @return boolean boolean
     */
    public static boolean isIllegal(String actionTime) {
        boolean isIllegal = false;
        String now = getTimeNow().substring(6, 8);
        try {
            int now_i = Integer.parseInt(now);
            int actionTime_i = Integer.parseInt(actionTime.substring(8, 10));
            //至少间隔48小时
            if ((now_i - actionTime_i) >= 3) {
                isIllegal = true;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return isIllegal;
    }

    /**
     * 把数据库查到的结果集转成json对象
     *
     * @param drList the dr list
     * @param status the status
     * @param msg    the msg
     * @return json object
     */
    public static JSONObject drJson(List<Object> drList, int status, String msg) {
        JSONObject record = new JSONObject();
        JSONArray recordArray = new JSONArray();
        for (int i = 0; i < drList.size(); i++) {
            DealRecord drObject = (DealRecord) drList.get(i);
            record.put("dealrecordId", drObject.getDealRecordId());
            record.put("time", drObject.getActionTime());
            record.put("userId", drObject.getUserId());
            record.put("action", actionType2front(drObject.getActionType()));
            record.put("money", drObject.getMoney());
            record.put("balance", formatBalance(drObject.getCurBalance()));
            recordArray.add(i, record);
        }
        return new JsonWrapperBuilder()
            .setStatus(status)
            .setMsg(msg)
            .setDataJsonArray("record", recordArray).build();
    }

    /**
     * 数据库字段和json中对应的value的转换
     *
     * @param num num
     * @return string
     */
    private static String actionType2front(String num) {
        // 创建Hashtable集合
        Hashtable<String, String> actionType2front = new Hashtable<>();
        actionType2front.put("0", "消费");
        actionType2front.put("1", "充值");
        //返回key对应的value值
        return actionType2front.get(num);
    }
}